package com.ruoyi.crm.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.crm.domain.Clue;
import com.ruoyi.crm.domain.vo.ClueTrackRecordVO;
import com.ruoyi.crm.domain.vo.MongoClueRecordVO;
import com.ruoyi.crm.enums.StatusType;
import com.ruoyi.crm.mapper.ClueMapper;
import com.ruoyi.crm.service.ClueTrackRecordService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author mr.huang [jie88888822@163.com]
 * @devTime 2022-06-21
 */
@Service
public class ClueTrackRecordServiceImpl implements ClueTrackRecordService {
	@Resource
	private ClueMapper clueMapper;
	@Resource
	private MongoTemplate mongoTemplate;

	@Override
	public List<MongoClueRecordVO> findClueTrackRecordVoByClueId(Long clueId) {
		//创建springBoot mongodb查询对象
		Query query = new Query(Criteria.where("clueId").is(clueId));
		//通过创建时间倒序排序
		query.with(Sort.by(Sort.Order.desc("createTime")));
		List<MongoClueRecordVO> recorddb =
				mongoTemplate.find(query, MongoClueRecordVO.class, "clue_recorddb");
		return recorddb;
	}

	/**
	 * 跟进线索：将状态改为：2  修改线索信息
	 * @param clueTrackRecordVo
	 * @return
	 */
	@Override
	public ClueTrackRecordVO addClueTrackRecordVo(ClueTrackRecordVO clueTrackRecordVo) {
		System.out.println("clueTrackRecordVo = " + clueTrackRecordVo);
		//跟进线索
		clueTrackRecordVo.setStatus(StatusType.FOLLOWING.getValue());
		clueMapper.updateClue(clueTrackRecordVoTOClue(clueTrackRecordVo));
		//将跟进线索数据保存在 mongodb
		MongoClueRecordVO mv = new MongoClueRecordVO();
		clueTrackRecordVoTOMongoClue(clueTrackRecordVo,mv);
		mongoTemplate.save(mv);
		return clueTrackRecordVo;
	}

	public Clue clueTrackRecordVoTOClue(ClueTrackRecordVO cv){
		Clue clue = new Clue();
		BeanUtils.copyProperties(cv,clue);
		clue.setUpdateBy(SecurityUtils.getUsername());
		clue.setUpdateTime(DateUtils.getNowDate());
		clue.setId(cv.getClueId());
		return clue;
	}

	public void clueTrackRecordVoTOMongoClue(ClueTrackRecordVO crv,MongoClueRecordVO mv){
		BeanUtils.copyProperties(crv, mv);
		mv.setType("0");
		mv.setClueId(crv.getClueId().intValue());
		mv.setCreateTime(DateUtils.getNowDate());
		mv.setNextTime(new Date(DateUtils.getNowToTwelve()));
		mv.setCreateBy(SecurityUtils.getUsername());
	}
}
